package com.frank.subject.application.mq.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.frank.subject.domain.entity.SubjectLikedMessage;
import com.frank.subject.infra.basic.entity.SubjectLiked;
import com.frank.subject.infra.basic.service.SubjectLikedService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2025/10/3
 * @description
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "jc-club-subject-liked", consumerGroup = "jc-club-subject-liked-consumer-group")
public class SubjectLikedListener implements RocketMQListener<String> {


    private final SubjectLikedService subjectLikedService;

    public SubjectLikedListener(SubjectLikedService subjectLikedService) {
        this.subjectLikedService = subjectLikedService;
    }

    @Override
    public void onMessage(String message) {
        // 2025 年 10 月 3 日 11:40:25 点赞消息处理完毕，返回成功响应
        log.info("receive message:{}", message);
        SubjectLikedMessage subjectLikedMessage = JSON.parseObject(message, SubjectLikedMessage.class);

        LambdaQueryWrapper<SubjectLiked> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SubjectLiked::getLikeUserId, subjectLikedMessage.getLikeUserId())
                .eq(SubjectLiked::getSubjectId, subjectLikedMessage.getSubjectId());
        SubjectLiked subjectLiked = new SubjectLiked();
        subjectLiked.setLikeUserId(subjectLikedMessage.getLikeUserId())
                .setSubjectId(subjectLikedMessage.getSubjectId())
                .setStatus(subjectLikedMessage.getStatus());
        // 根据题目 ID 和用户 ID 进行判断，如果有记录就是更新，没有记录就是新增
        subjectLikedService.saveOrUpdate(subjectLiked, queryWrapper);
    }
}
